﻿using Elmah;
using nplJobsBLL.Common;
using nplJobsBLL.ProcessJob;
using nplJobsBLL.ProcessJobSeeker;
using nplJobsCommon.Common;
using nplJobsCommon.JobSeeker;
using nplJobsDAL.Select;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class JobSeeker_JobAlert : System.Web.UI.Page
{
    public static List<string> lstSkills;

    #region LoadCountry
    public void LoadCountry()
    {
        try
        {
            ProcessCountry country = new ProcessCountry();
            country.invoke();
            ddlCountry.DataSource = country.Country;
            ddlCountry.DataTextField = "Name";
            ddlCountry.DataValueField = "ID";
            //ddlCountry.DataBind();


            ListItem l = new ListItem("--Select  a country--", "-1", true);
            ddlCountry.Items.Insert(0, l);
            ListItem lstDefault = ddlCountry.Items.FindByText("Nepal");
            if (lstDefault != null)
                lstDefault.Selected = true;
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());

        }
    }
    #endregion

    #region PopulateCity
    private void PopulateCity(int countryID)
    {

        ProcessSelectCity city = new ProcessSelectCity();
        city.countryID = countryID;
        city.invoke();
        ddlCity.ClearSelection();
        ddlCity.DataSource = city.City;
        ddlCity.DataTextField = "Name";
        ddlCity.DataValueField = "ID";
        ddlCity.SelectedValue = null;
        ddlCity.DataBind();

        ListItem l = new ListItem("--Select  a city--", "-1", true);
        ddlCity.Items.Insert(0, l);
    }
    #endregion

    #region LoadSkill
    [WebMethod]
    public static List<string> LoadSkill()
    {
        List<string> skills = new List<string>();

        bool count = lstSkills != null && lstSkills.All(x => x == "");

        if (lstSkills != null && !count)
        {
            skills = lstSkills;
        }
        else
        {
            skills.Add("No data");
        }

        return skills;
    }
    #endregion

    #region LoadData
    /// <summary>
    /// 
    /// </summary>
    private void LoadData()
    {
        try
        {
            MembershipUser userInfo = Membership.GetUser(User.Identity.Name);
            if (userInfo != null)
            {
                Guid jobSeekerID = (Guid)userInfo.ProviderUserKey;

                List<JobAlert> jobAlerts = new List<JobAlert>();
                ProcessSelectJobAlert selectJobAlerts = new ProcessSelectJobAlert();
                selectJobAlerts.JobAlertID = -1;
                selectJobAlerts.JobseekerID = jobSeekerID;
                selectJobAlerts.invoke();
                jobAlerts = selectJobAlerts.JobAlert;

                if (jobAlerts != null)
                {
                    gvData.DataSource = jobAlerts;
                    gvData.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }
    #endregion

    #region LoadDefaultName
    private void LoadDefaultName()
    {
        try
        {
            //JobAlert obj = new JobAlert();
            //MembershipUser userInfo = (MembershipUser)Session["userInfo"];
            //Guid userID = (Guid)userInfo.ProviderUserKey;
            //obj.AlertName = "";
            //obj.CategoryID = -1;
            //obj.Frequency = -1;
            //obj.LocationID = -1;
            //obj.SalaryRangeID = -1;
            //obj.UserID = userID;
            //obj.WorkTypeID = -1;

            //List<JobAlert> lst = ProcessJobAlert.GetList(obj);
            //List<JobAlert> lst1 = lst.Where(c => c.AlertName.Contains("alert job")).ToList();

            //if (lst1 == null)
            //{
            //    txtAlertName.Text = "alert job 1";
            //}
            //else
            //{
            //    txtAlertName.Text = "alert job " + (lst1.Count == 0 ? "1" : (lst1.Count + 1).ToString());
            //}

        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }
    #endregion

    #region GetAlertFrequency
    private void GetAlertFrequency()
    {
        try
        {
            ProcessJobAlertFrequency jobAlertFrequency = new ProcessJobAlertFrequency();
            jobAlertFrequency.JobAlertFrequencyID = -1;
            jobAlertFrequency.invoke();

            if (jobAlertFrequency != null)
            {
                rdoFrequency.DataSource = jobAlertFrequency.JobAlertFrequency;
                rdoFrequency.DataTextField = "Frequency";
                rdoFrequency.DataValueField = "ID";
                rdoFrequency.DataBind();
            }
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);

        }
    }
    #endregion

    #region Load_Location
    public List<Location> Load_Location()
    {
        ProcessLocation location = new ProcessLocation();
        try
        {
            location.LocationID = -1;
            location.invoke();
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return location.Location;
    }
    #endregion

    #region Load_Category
    public List<JobCategory> Load_Category()
    {
        ProcessJobCategory jobCategory = new ProcessJobCategory();
        try
        {
            jobCategory.invoke();
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return jobCategory.JobCategory;
    }
    #endregion

    #region Load_CareerLevel
    public List<JobType> Load_CareerLevel()
    {
        ProcessJobType careerLevel = new ProcessJobType();
        try
        {
            careerLevel.countryID = -1;
            careerLevel.invoke();
        }
        catch (Exception ex) {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }

        return careerLevel.JobType;
    }
    #endregion

    #region Load_SalaryRange
    public List<SalaryRange> Load_SalaryRange()
    {
        ProcessSalaryRange salaryRange = new ProcessSalaryRange();
        try
        {
            salaryRange.invoke();
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return salaryRange.SalaryRange;
    }
    #endregion

    #region ClearControls
    private void ClearControls()
    {
        //lblSaveMsg.Text = string.Empty;
        txtAlertName.Text = "";
        txtKeyWords.Text = "";
        ddlCategory.SelectedIndex = -1;
        ddlCountry.SelectedIndex = -1;
        ddlCity.SelectedIndex = -1;
        ddlSalaryRange.SelectedIndex = -1;
        ddlWorkType.SelectedIndex = -1;
        rdoFrequency.SelectedIndex = -1;
        chkAlertActivate.Checked = false;
        hdJobalertID.Value = "";
        lstSkills = null;
        //ScriptManager.RegisterStartupScript(unlJobAlert, unlJobAlert.GetType(), "scriptKey", "$('#allowSpacesTags').tagit({ itemName: 'teamId',fieldName: 'teamName',availableTags: '',allowSpaces: true,caseSensitive: false,removeConfirmation: true,maxTags: 2,sortable: true,select: true,placeholderText: 'Add skills...'});", true);

        if (rdoFrequency.Items != null && rdoFrequency.Items.Count > 0)
        {
            if (rdoFrequency.Items.FindByText("Daily") != null)
            {
                rdoFrequency.Items.FindByText("Daily").Selected = true;
            }
        }
        LoadDefaultName();
    }
    #endregion

    #region ShowDetails
    private void ShowDetails(int id)
    {
        try
        {
            //JobAlert obj = new JobAlert();
            //MembershipUser userInfo = (MembershipUser)Session["userInfo"];
            //Guid userID = (Guid)userInfo.ProviderUserKey;
            //obj.ID = id;
            //obj.AlertName = "";
            //obj.CategoryID = -1;
            //obj.Frequency = -1;
            //obj.LocationID = -1;
            //obj.SalaryRangeID = -1;
            //obj.UserID = userID;
            //obj.WorkTypeID = -1;
            //List<JobAlert> lst = ProcessJobAlert.GetList(obj);

            //if (lst != null)
            //{
            //    txtAlertName.Text = lst[0].AlertName;
            //    rdoFrequency.SelectedValue = lst[0].Frequency.ToString();
            //    txtKeyWords.Text = lst[0].Keyword;
            //    hdID.Value = lst[0].ID.ToString();
            //    if (lst[0].CategoryID > 0) ddlCategory.SelectedValue = lst[0].CategoryID.ToString();
            //    if (lst[0].CategoryID > 0) ddlCategory.SelectedValue = lst[0].CategoryID.ToString();
            //    if (lst[0].LocationID > 0) ddlLocation.SelectedValue = lst[0].LocationID.ToString();
            //    if (lst[0].SalaryRangeID > 0) ddlSalaryRange.SelectedValue = lst[0].SalaryRangeID.ToString();
            //    if (lst[0].WorkTypeID > 0) ddlWorkType.SelectedValue = lst[0].WorkTypeID.ToString();
            //}
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }
    #endregion

    #region Events
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (!ddlCountry.SelectedItem.Text.Equals("Nepal"))
            {
                ddlCity.Enabled = false;
            }
            else
            {
                ddlCity.Enabled = true;
            }

            int countryID = ddlCountry.SelectedValue != null ? int.Parse(ddlCountry.SelectedValue) : -1;
            PopulateCity(countryID);
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    } 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
            Response.Redirect("~/Default.aspx", false);

        if (!IsPostBack)
        {
            Page.Title = "npljobs.com || Job alert";


            Label lblTitle = Page.Master.FindControl("lblTitle") != null ? (Label)Page.Master.FindControl("lblTitle") : new Label();
            lblTitle.Text = "Job alert(s)";

            //hdID.Value = "-1";
            GetAlertFrequency();
            LoadData();
            LoadDefaultName();
            LoadDataOnControls(-1);
            LoadCountry();
            PopulateCity(140);

            if (rdoFrequency.Items != null && rdoFrequency.Items.Count > 0)
            {
                if (rdoFrequency.Items.FindByText("Daily") != null)
                {
                    rdoFrequency.Items.FindByText("Daily").Selected = true;
                }
            }
        }
        else
            lstSkills = hdnSelectedTags.Value != null ? hdnSelectedTags.Value.ToString().Split(new char[] { ',' }).ToList() : null; ;

    }
    protected void lnkAlert_Command(object sender, CommandEventArgs e)
    {
        int jobAlertID = e.CommandArgument != null ? int.Parse(e.CommandArgument.ToString()) : 0;
        hdJobalertID.Value = jobAlertID.ToString();
        LoadDataOnControls(jobAlertID);
        lblSaveMsg1.Text = string.Empty;
    }
    protected void imgDelete_Click(object sender, ImageClickEventArgs e)
    {
        lblSaveMsg1.Text = string.Empty;

        ImageButton btndetails = sender as ImageButton;
        GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
        Session["JobAlertID"] = gvData.DataKeys[gvrow.RowIndex].Value.ToString();
        Session["AlertName"] = gvrow.Cells[0].Text;
        lblText.InnerText = "Are you sure you want to delete : " + Session["AlertName"];
        ModalPopupExtender1.Show();

    }
    protected void btnYes_Click(object sender, ImageClickEventArgs e)
    {
        lblSaveMsg1.Text = string.Empty;

        MembershipUser userInfo = Membership.GetUser(User.Identity.Name);
        Guid jobSeekerID = (Guid)userInfo.ProviderUserKey;

        ProcessDeleteJobSeekerJobAlert deleteJobSeekerJobAlert = new ProcessDeleteJobSeekerJobAlert();
        int alertID = -1;

        if (Session["JobAlertID"] != null && !string.IsNullOrEmpty(Session["JobAlertID"].ToString()))
        {
            bool altID = int.TryParse(Session["JobAlertID"].ToString(), out alertID);
        }

        deleteJobSeekerJobAlert.JobAlertID = alertID;
        deleteJobSeekerJobAlert.JobSeekerId = jobSeekerID;
        deleteJobSeekerJobAlert.invoke();
        bool isDeleted = deleteJobSeekerJobAlert.IsDeleted;
        if (isDeleted)
        {
            ClearControls();
            LoadData();

            lblSaveMsg1.ForeColor = System.Drawing.Color.Green;
            lblSaveMsg1.Text = "Data deleted successfully";
             
        }
        else
        {
            lblSaveMsg1.ForeColor = System.Drawing.Color.Red;
            lblSaveMsg1.Text = "Data deletion error.Please try again.";
        }
        ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsgAlert", "ClearSaveMsgAlert();", true);

    }
    protected void btnCancel_Click(object sender, ImageClickEventArgs e)
    {
        ClearControls();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Page.Validate("valJobAlert");
        if (Page.IsValid)
        {

            lblSaveMsg1.Text = string.Empty;

            MembershipUser userInfo = Membership.GetUser(User.Identity.Name);
            Guid jobSeekerID = (Guid)userInfo.ProviderUserKey;

            JobAlert jobAlert = new JobAlert();
            jobAlert.AlertName = txtAlertName.Text;
            jobAlert.CategoryID = ddlCategory.SelectedIndex > 0 ? int.Parse(ddlCategory.SelectedValue) : -1;
            jobAlert.FrequencyID = int.Parse(rdoFrequency.SelectedValue);
            //jobAlert.CountryID = ddlCountry.SelectedIndex > 0 ? int.Parse(ddlCountry.SelectedValue) : -1;
            //jobAlert.CityID = ddlCity.SelectedIndex > 0 ? int.Parse(ddlCity.SelectedValue) : -1;
            jobAlert.SalaryRangeID = ddlSalaryRange.SelectedIndex > 0 ? int.Parse(ddlSalaryRange.SelectedValue) : -1;
            jobAlert.WorkTypeID = ddlWorkType.SelectedIndex > 0 ? int.Parse(ddlWorkType.SelectedValue) : -1;
            jobAlert.Keyword = txtKeyWords.Text;
            jobAlert.Skills = hdnSelectedTags.Value;
            jobAlert.UpdatedDate = System.DateTime.Now;
            jobAlert.JobSeekerID = jobSeekerID;

            int alertID = -1;

            if (!String.IsNullOrEmpty(hdJobalertID.Value))
            {
                bool alt = int.TryParse(hdJobalertID.Value.ToString(), out alertID);
            }
            jobAlert.JobAlertID = alertID;
            jobAlert.IsActive = chkAlertActivate.Checked;

            ProcessInsertJobAlert processInsertJobAlert = new ProcessInsertJobAlert();
            processInsertJobAlert.JobAlert = jobAlert;
            processInsertJobAlert.JobSeekerID = jobSeekerID;
            processInsertJobAlert.JobAlertID = alertID;
            processInsertJobAlert.invoke();
            long lastJobAlertID = processInsertJobAlert.lastJobAlertID;

            if (lastJobAlertID > 0)
            {
                lblSaveMsg1.ForeColor = System.Drawing.Color.Green;
                lblSaveMsg1.Text = "Data saved successfully";
                lblSaveMsg1.Visible = true;
                ClearControls();
                LoadData();
            }
            else
            {
                lblSaveMsg1.ForeColor = System.Drawing.Color.Red;
                lblSaveMsg1.Text = "Data saving error.Please try again.";
            }

            ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsgAlert", "ClearSaveMsgAlert();", true);
            //ScriptManager.RegisterStartupScript(this, GetType(), " reload", "spShow();$('#div1-wrapper').load(location.href  + ' #div1'); ClearSaveMsg();", true);
        }

        btnAddNew.Enabled = true;
        
    }
    protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Details")
        {
            try
            {
                string strId = e.CommandArgument.ToString();
                ShowDetails(int.Parse(strId));
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
        else if (e.CommandName == "del")
        {
            JobAlert obj = new JobAlert();

            int jobAlertID = int.Parse(e.CommandArgument.ToString());
            ///obj.UserID = Guid.Empty;

            ProcessDeleteJobSeekerJobAlert jsAlert = new ProcessDeleteJobSeekerJobAlert();
            jsAlert.JobAlertID = jobAlertID;
            jsAlert.invoke();
            bool isDeleted = jsAlert.IsDeleted;

            //ProcessJobAlert.Delete(obj);
            if (isDeleted)
            {
                // ClearControls();

                lblSaveMsg1.ForeColor = System.Drawing.Color.Green;
                lblSaveMsg1.Text = "Data deleted successfully";

                LoadData();
                //btnCancel_Click(null, null);
            }
            else
            {
                lblSaveMsg1.ForeColor = System.Drawing.Color.Red;
                lblSaveMsg1.Text = "Error Deleting data!";
            }
        }

        ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsg", "ClearSaveMsg();", true);

    }
    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        ClearControls();
        lblSaveMsg1.Text = string.Empty;
        btnAddNew.Enabled = false;
    }
    protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var chkStatus = (CheckBox)e.Row.FindControl("chkActive");
            Label lblStatuss = (Label)e.Row.FindControl("lblStatus");

            if (chkStatus.Checked == true)
            {
                lblStatuss.Text = "Active";
                lblStatuss.ForeColor = Color.Green;
            }
            else
            {
                lblStatuss.Text = "In Active";
                lblStatuss.ForeColor = Color.Red;
            }
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        ClearControls();
        btnAddNew.Enabled = true;
    }

    #endregion

    #region LoadDataOnControls
    private void LoadDataOnControls(int jobAlertID)
    {

        MembershipUser userInfo = Membership.GetUser(User.Identity.Name);
        if (userInfo != null)
        {
            Guid jobSeekerID = (Guid)userInfo.ProviderUserKey;

            List<JobAlert> jobAlerts = new List<JobAlert>();
            ProcessSelectJobAlert selectJobAlerts = new ProcessSelectJobAlert();
            selectJobAlerts.JobAlertID = jobAlertID;
            selectJobAlerts.JobseekerID = jobSeekerID;
            selectJobAlerts.invoke();
            jobAlerts = selectJobAlerts.JobAlert;

            if (jobAlerts != null && jobAlerts.Count > 0)
            {
                JobAlert ja = jobAlerts.FirstOrDefault();
                txtAlertName.Text = ja.AlertName;
                txtKeyWords.Text = ja.Keyword;
                ddlCategory.SelectedValue = ja.CategoryID.ToString();
                //ddlCountry.SelectedValue = ja.CountryID.ToString();
                //ddlCity.SelectedValue = ja.CityID.ToString();
                ddlSalaryRange.SelectedValue = ja.SalaryRangeID.ToString();
                ddlWorkType.SelectedValue = ja.WorkTypeID.ToString();
                rdoFrequency.SelectedValue = ja.FrequencyID.ToString();
                chkAlertActivate.Checked = ja.IsActive;
                hdJobalertID.Value = ja.JobAlertID.ToString();

                Session["Skills"] = ja.Skills;
                lstSkills = Session["Skills"] != null ? Session["Skills"].ToString().Split(new char[] { ',' }).ToList() : null;

            }
        }
    }
    #endregion

}